<template>
  <div>
    <div ref="terminalContainer"></div>
  </div>
</template>

<script>
import {Terminal} from "xterm";
import "xterm/css/xterm.css";
import SockJS from "sockjs-client";
// import Stomp from "stompjs";
// import {cloneDeep} from "lodash-es";

export default {
  name: "windowShellComponent",
  data() {
    return {
      socket: null,
      term: null,
      stompClient: null,
      socketOptions: {
        url: "/amo/amo-socket", // sock连接地址
        subscribes: ["/amo/"], // 订阅地址前缀，真实地址为：/amo/${主机id},可根据自己情况调整
        sendUrl: "/amo/webssh/recever", // 发送消息地址
      },
    }
  },
  methods: {
    initWebSSH() {
      this.$nextTick(() => {
        this.openTerminal();
      });
    },
    disconnect() {
      // 断开连接
      this.stompClient.disconnect();
      this.term.dispose();
      console.log("Disconnected!");
    },
    onSendMsg(data) {
      this.stompClient.send(this.socketOptions.sendUrl, {}, JSON.stringify(data));
    },
    createSocket(term) {

      const that = this;

      /*** start 发送给服务器的数据格式，可自定义 ***/
      let msgObj = {
        ip: "118.178.239.213",
        port: 22,
        msg: "",
        status: "CONNECT"
      };
      /*** end 发送给服务器的数据格式，可自定义 ***/

          // 订阅消息
      const onSubscribes = () => {
            const subscribes = this.socketOptions.subscribes;
            subscribes.forEach(url => {
              // 订阅消息地址
              const link = url + "自定义参数，比如主机ip，需与后台协商";

              this.stompClient.subscribe(
                  link,
                  msg => {
                    let {body} = msg;
                    body = JSON.parse(body);
                    const {bizCode, val} = body;
                    console.log(bizCode + "_received", val);
                    term.write(val);
                  },
                  {}
              );
            });
          };

      // 监听键盘输入，并发送给服务器
      const onKeyBoard = () => {
        // 连接成功后监听terminal输入
        term.onData(str => {

          msgObj.msg = str;
          msgObj.status = "COMMAND";

          this.onSendMsg(msgObj);
        });
      };

      // 连接
      this.socket = new SockJS(this.socketOptions.url, null, {
        "transports": ["websocket"],
        timeout: 15000
      });
      // this.stompClient = Stomp.over(this.socket);
      this.stompClient.connect(
          {}, () => {
            onKeyBoard();
            that.onSendMsg(msgObj);
            // 接收订阅消息
            onSubscribes();
            term.writeln("Connection Successful!");
            term.writeln("Type some keys and commands to play around.");
            term.focus();
          }, () => {
            term.writeln("");
            term.writeln("Connection Fail!");
            term.writeln("");
            console.log("***连接失败***");
          }
      );
    },

    /**
     * @description socket连接前准备
     * @param {object} term
     * @returns {*}
     */
    runFakeTerminal(term) {
      if (term._initialized) {
        return;
      }
      term._initialized = true;
      //在页面上显示连接中...
      term.writeln("Connecting...");
    },

    /**
     * @description 实例化 xterm
     * @param {*}
     * @returns {*}
     */
    openTerminal() {
      const terminalDom = this.$refs.terminalContainer
      const term = new Terminal({
        rows: 40, // 行数
        cursorBlink: true, // 光标闪烁
        cursorStyle: "block", // 光标样式  null | 'block' | 'underline' | 'bar'
        scrollback: 10,//终端中的回滚量
        tabStopWidth: 8, //制表宽度
        disableStdin: false, //是否应禁用输入。
        rendererType: "canvas", //渲染类型
        theme: {
          foreground: "yellow", //字体
          background: "#060101", //背景色
          cursor: "help",//设置光标
        }
      });
      term.open(terminalDom);
      this.term = term;
      this.runFakeTerminal(term);

      // 建立socket连接
      this.createSocket(term);
    },
  },
  mounted() {
    this.initWebSSH()
  },
}
</script>

<style scoped>

</style>